/**
 * Created by sxwu on 14-2-15.
 */


var fields_all = "adlogid,adid,customerid,optdatetime";

/**
 * 模块依赖
 */
var db = require("../lib/db");


//查找记录
exports.select = function(adid, handler) {
    db.execQuery({
        "sql": "SELECT * FROM adlog WHERE adid=?",
        "args": [adid],
        "handler": handler
    });

};
//插入记录
exports.insert = function(adlog, handler) {
    db.execQuery({
        "sql": "insert into adlog(adid,customerid,optdatetime) " +
            "values(?,?,?)",
        "args":[
            adlog.adid,
            adlog.customerid,
            adlog.optdatetime],
        "handler": handler
    });
};

//根据来源分类查找用户在各整点访问次数
exports.selectForStat = function(userid, handler) {
    db.execQuery({
        "sql": "SELECT DATE_FORMAT(a.optdatetime,'%Y-%m-%d %H:00') hour,COUNT(a.adlogid) count, b.adname adname" +
            " FROM adlog a,adinfo b " +
            " WHERE a.adid=b.adid AND b.userid=? GROUP BY hour,adname",
        "args": [userid],
        "handler": handler
    });
};

//根据时间范围查询
exports.selectForStatByeDate = function(range, handler) {
    db.execQuery({
        "sql": "SELECT DATE_FORMAT(a.optdatetime,'%Y-%m-%d %H:00') hour,COUNT(a.adlogid) count, b.adname adname" +
            " FROM adlog a,adinfo b " +
            "WHERE a.adid=b.adid AND b.userid=? " +
            "and optdatetime between DATE_FORMAT(?,'%Y-%m-%d 00:00') AND  DATE_FORMAT(?,'%Y-%m-%d 23:59') GROUP BY hour,adname",
        "args": [
            range.userid,
            range.begindate,
            range.enddate],
        "handler": handler
    });
};

//遍历记录
exports.findAll = function(handler) {
    db.execQuery({
        "sql": "SELECT * FROM adlog ORDER BY adid asc",
        "handler": handler
    });
};
